#include "Frustum.h"

#include <math.h>
#include "Object.h"
#include "Primitive.h"
#include "Sphere.h"

#include "Scene.h"

#include "Define.h"
#include <math.h>

Frustum::Frustum()
{
} // Constructeur

Frustum::~Frustum()
{
} // Destructeur

void Frustum::buildFrustum(Math::Vector &pos, Math::Vector &right, Math::Vector &up, Math::Vector &look, 
	float nearClip, float farClip, float ratio)
{
	m_Position = pos;

	nc = m_Position+look*nearClip;
	fc = m_Position+look*farClip;

	m_Plane[NEAR] = Math::Plane(nc, look);
	m_Plane[FAR] = Math::Plane(fc, look.inverse());
	/*
	m_Plane[TOP] = Math::Plane(nc+up*nh, ((nc+up*nh)-m_Position).normal().cross(right));
	m_Plane[BOTTOM] = Math::Plane(nc-up*nh, ((nc-up*nh)-m_Position).normal().cross(right));
	m_Plane[LEFT] = Math::Plane(nc-right*nw, ((nc-right*nw)-m_Position).normal().cross(up));
	m_Plane[RIGHT] = Math::Plane(nc+right*nw, ((nc+right*nw)-m_Position).normal().cross(up));*/
} // buildFrustum

void Frustum::update(Scene *pScene)
{
	m_Visible.clear();
	for (size_t i = 0; i < pScene->getNumObject(); i++) {
		if (intersects(pScene->getObject(i)))
			m_Visible.push_back(pScene->getObject(i));
	}

	#ifdef DEBUG
		printf("%d\n", m_Visible.size());
	#endif
} // update

bool Frustum::intersects(Object *pObj)
{
	float t = 0.0f;
	for (int i = 0; i < 6; i++) {
		if (pObj->intersects(m_Plane[i], t) == Object::OUTSIDE) 
			return false;
	}

	return true;
} // intersects
